525E - Anya and Cubes - CodeForces Solution


binary search bitmasks brute force dp math meet-in-the-middle *2100

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

using ll = long long;

const int N = 105;

ll n, k, S;
ll factorial[19];



void solve(int idx, ll sum, int ex, vector<int> &v,  map<ll, vector<int>> &m) {
    if (idx == v.size()) return void(m[sum].push_back(ex));
    
    solve(idx + 1, sum, ex, v, m);
    solve(idx + 1, sum + v[idx], ex, v, m);
    if (v[idx] < 19 && sum + factorial[v[idx]] <= S)
        solve(idx + 1, sum + factorial[v[idx]], ex + 1, v, m);
}


int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    
    cin >> n >> k >> S;
    vector<int> a(n); 
    for (int i = 0; i < n; i++) cin >> a[i];
    vector<int> v1(a.begin(), a.begin() + n/2), v2(a.begin() + n/2, a.end());
    
    factorial[0] = 1;
    for (int i = 1; i < 19; i++) 
        factorial[i] = factorial[i - 1] * i;
        
    map<ll, vector<int>> m1, m2; // map for finding the elements with the number of ! with it.
    
    solve(0, 0, 0, v1, m1);
    solve(0, 0, 0, v2, m2);
    m1[0] = {0};
    m2[0] = {0};
    
    for (auto u : m2) 
        sort(m2[u.first].begin(), m2[u.first].end()); 
    
    ll ans = 0;
    for (auto u : m1) {
        ll target = S - u.first;
        if (m2.find(target) != m2.end()) {
            for (auto l : m1[u.first]) {
                auto it = upper_bound(m2[target].begin(), m2[target].end(), k - l);
                ans += it - m2[target].begin(); 
            }
        }
    }
    //here
    cout << ans << "\n";
    
    return 0;
}
 				 	 	  			  		 								  		


Comments

Submit
0 Comments
More Questions

167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation